﻿using MyPlanSilverlight.Models;
using MyPlanSilverlight.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MyPlanSilverlight
{
    public partial class MainPage : UserControl
    {

        private static Cache systemCache = Cache.Instance;

        public MainPage()
        {
            InitializeComponent();
            if (systemCache["Account"] != null)
            {
                this.Content = new UserCenter();
            }
        }

        private void myButton_Click(object sender, RoutedEventArgs e)
        {
            string account = tbAccount.Text.Trim();
            string password = tbPassword.Text.Trim();

            string url = App.Current.Host.Source.ToString();
            url = url.Substring(0, url.IndexOf('/', 7) + 1) + "api/user/login";
            Uri URL = new Uri(url);

            HttpHelper helper = new HttpHelper(URL, "POST",
                new KeyValuePair<string, string>("Account", account),
                new KeyValuePair<string, string>("Password", password));
            helper.ResponseComplete += new HttpResponseCompleteEventHandler(this.CommandComplete);
            helper.Execute();

        }

        private void CommandComplete(HttpResponseCompleteEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                Response response = Response.Init(e.Response);

                if (response.Status == ConstanCodes.SUCCESS)
                {
                    User user = response.toEntity<User>();

                    systemCache["Id"] = user.Id;
                    systemCache["Name"] = user.Name;
                    systemCache["Account"] = user.Account;

                    this.Content = new UserCenter();
                }
                else if (response.Status == ConstanCodes.ACCOUNT_PASSWORD_ERROR)
                {
                    MessageBox.Show("账号密码不正确！");
                }
                else if (response.Status == ConstanCodes.SERVER_ERROR)
                {
                    MessageBox.Show("服务器错误");
                }  
            });
        }

        private void regist_Click(object sender, RoutedEventArgs e)
        {
            this.Content = new RegistPage();
        }

     
    }
}
